package com.shundr.auth.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.j256.ormlite.misc.VersionUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.shundr.auth.channel.R;
import com.shundr.auth.base.BaseActivity;
import com.shundr.auth.common.dao.AttributeDao;
import com.shundr.auth.common.util.FileHelper;
import com.shundr.auth.common.view.SharedPrefUtil;
import com.shundr.auth.frame.constant.LConstants;
import com.shundr.auth.frame.http.HttpRequest;
import com.shundr.auth.frame.http.LHttpRequest;
import com.shundr.auth.frame.util.GetVersionUtil;
import com.shundr.auth.frame.util.LLogger;
import com.shundr.auth.frame.util.StringUtil;
import com.shundr.auth.frame.util.ToastHelper;
import com.shundr.auth.user.dao.AreaDao;
import com.shundr.auth.user.dao.StaffDao;
import com.shundr.auth.user.http.UserRequest;
import com.shundr.auth.user.model.StaffInfo;

public class MainActivity extends BaseActivity {

	private Button btnAdd;
	private Button btnBindUser;
	private Button btnFindUser;
	
	private ImageView ig_QrCode;

	private SharedPrefUtil shPrefUtil;
	private ImageLoader mImageLoader;
	private DisplayImageOptions options;

	private String qrCodeUrl;

	private AreaDao areaDao;
	private String fileName;
	private static final int COPY_FILE_SUCCESS = 401;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UserRequest.CREATE_STAFF_QRCODE_SUCCESS:
				qrCodeUrl = (String) msg.obj;
				mImageLoader.displayImage(qrCodeUrl, ig_QrCode, options);
				ToastHelper.toastShort(mContext, "二维码生成成功！");
				break;
			case LHttpRequest.REQUEST_FAILED:
				ToastHelper.toastShort(mContext, msg.obj.toString());
				break;
			case COPY_FILE_SUCCESS:
				ToastHelper.toastLong(mContext, "已经成功下载二维码！\n" + fileName);
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		tvTitle.setText(getTitle() + GetVersionUtil.getVersionName(mContext));

		btnAdd = (Button) findViewById(R.id.btn_add);
		btnBindUser = (Button) findViewById(R.id.btn_bind_user);
		btnFindUser = (Button) findViewById(R.id.btn_find_user);
		

		btnAdd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(mContext, RegisterActivity.class));
			}
		});

		btnBindUser.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(mContext, BindUserActivity.class));// 绑定用户
			}
		});

		btnFindUser.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				startActivity(new Intent(mContext, AuthUserByDateActivity.class));// 用户列表
			}
		});

		findViewById(R.id.btn_change_pwd).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				
				String phone = shPrefUtil.getString(LConstants.STAFF_PHONE, "");
				
				if (StringUtil.isNullVal(shPrefUtil.getString(LConstants.STAFF_PHONE, ""))) {
					ToastHelper.toastShort(mContext, "当前用户信息获取失败，请重新登录尝试！");
					return;
				}
				
				startActivity(new Intent(mContext, ChangePasswordActivity.class));// 我的渠道

			}
		});

		findViewById(R.id.btn_add_truck).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View arg0) {
						startActivity(new Intent(mContext,
								AddSocialTruckActivity.class));// 添加社会车辆
					}
				});

		findViewById(R.id.btn_truck_list).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View arg0) {
						startActivity(new Intent(mContext,
								SocialTruckListActivity.class));// 社會車輛列表
					}
				});

		shPrefUtil = new SharedPrefUtil(this, LConstants.PRE_NAME);

		ig_QrCode = (ImageView) findViewById(R.id.ig_QrCode);

		ig_QrCode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (ig_QrCode.getDrawable() == null) {
					new UserRequest(mContext, mHandler).reCreateStaffQrCode();
				} else {

					final File file = mImageLoader.getDiskCache()
							.get(qrCodeUrl);
					fileName = LConstants.QRCODE_PATH
							+ shPrefUtil.getString(
									ChannelLoginActivity.LAST_USER_NAME, "")
							+ ".png";
					final File out = new File(fileName);
					if (!out.exists()) {
						new Thread(new Runnable() {

							@Override
							public void run() {

								try {
									FileHelper.copyFile(file, out);
									Message message = mHandler.obtainMessage();
									message.what = COPY_FILE_SUCCESS;
									mHandler.sendMessage(message);
								} catch (IOException e) {
									// TODO Auto-generated catch block
									LLogger.e(e.getMessage());
								}

							}
						}).start();
					}
				}
			}
		});

		qrCodeUrl = shPrefUtil.getString(LConstants.STAFF_QRCODE_PIC, "");

		initOptions();
		mImageLoader = ImageLoader.getInstance();
		if (!StringUtil.isNull(qrCodeUrl)) {
			mImageLoader.displayImage(qrCodeUrl, ig_QrCode, options);
		}

		areaDao = new AreaDao();

		new InitAreaDaoThread().start();
		
	}

	private void initOptions() {
		options = new DisplayImageOptions.Builder().cacheOnDisk(true)
				.cacheInMemory(true).build();
	}

	@Override
	protected void onDestroy() {
		releaseImageView(ig_QrCode);
		super.onDestroy();
	}

	class InitAreaDaoThread extends Thread {
		@Override
		public void run() {
			if (areaDao.isNeedInit()) {
				areaDao.initArea(mContext);
				LLogger.e("success init areaDao");
			}

		}
	}

	class RefreshStaffThread extends Thread {

		private List<StaffInfo> list = new ArrayList<StaffInfo>();

		public RefreshStaffThread(List<StaffInfo> list) {
			this.list = list;
		}

		@Override
		public void run() {
			StaffDao staffDao = new StaffDao();
			staffDao.syncData(list);
		}
	}
}
